package com.xg.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.xg.sys.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Objects;

/**
 * Mybatis-Plus配置类
 * @author tzt
 */
@Configuration
@Slf4j
@MapperScan({"com.xg.**.mapper"})
public class MybatisPlusConfig {
    @Bean
    public OptimisticLockerInterceptor mybatisPlusInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                SysUser user = getUserId(metaObject);
                if (!Objects.isNull(user)) {
                    this.strictInsertFill(metaObject, "createUserId", Long.class, user.getId());
                }
                this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                SysUser user = getUserId(metaObject);
                if (!Objects.isNull(user)) {
                    this.strictUpdateFill(metaObject, "updateUserId", Long.class, user.getId());
                }
                this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            }

            private SysUser getUserId(MetaObject metaObject) {
                try {
                    return (SysUser) SecurityUtils.getSubject().getPrincipal();
                } catch (Exception e) {
                    log.info("填充用户ID失败，填充信息为：{}", metaObject.toString());
                }
                return null;
            }
        };
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        /* 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false*/
        paginationInterceptor.setOverflow(true);
        /* 设置最大单页限制数量，默认 500 条，-1 不受限制*/
        paginationInterceptor.setLimit(500);
        return paginationInterceptor;
    }
}
